package com.studentportalen;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;

public class ScheduleActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);

        //Uri uri = Uri.parse();
        try
        {
        	//Get courses
        	DBHelper db = Global.getDBHelper();
        	Cursor c = db.getStudentRegistered(Global.getStudent());
        	String objects = "";
        	//201967.182,201015.182
        	//if(c.moveToFirst()){
	        	while(c.moveToNext()){
	        		objects += c.getInt(c.getColumnIndex("scheduleId")) + ".182,";
	        	}
        	//}
	        objects = objects.substring(0, objects.length()-1);
        	
	        // open a connection to the desired URL
	        URL url = new URL("https://web.timeedit.se/chalmers_se/db1/timeedit/p/public/r.html?sid=3&h=t&p=20111017.x%2C20111222.x&objects=" + objects + "&ox=0&types=0&fe=0#formatlinks");
	        URLConnection conn = url.openConnection();
	        
	        //use the cleaner to "clean" the HTML and return it as a TagNode object	
	        InputStreamReader isr = new InputStreamReader(conn.getInputStream());
	        BufferedReader reader = new BufferedReader(isr);
	        
	        String line = "";
	        String csvUrl = "";
	        
	        while((line = reader.readLine()) != null){
	        	if(line.contains("CSV")){
	        		int start = line.indexOf('"') + 1;
	        		Log.d("studentportalen","ScheduleActivity.onCreate()>start position of'\"':" + start);
	        		int end = line.substring(start, line.length()).indexOf('"');
	        		Log.d("studentportalen","ScheduleActivity.onCreate()>end position of'\"':" + end);
	        		csvUrl = line.substring(start, end);
	        		break;
	        	}
	        }
	        
	        List<Lecture> values = getLectures(csvUrl);
	        
	        ScheduleArrayAdapter adapter = new ScheduleArrayAdapter(this,
	        		R.layout.list_item_schedule, values);
	        
	        setListAdapter(adapter);
	        
        }
        catch(Exception ex){
        	// handle exception
        	Log.d("studentportalen",ex.getMessage());
        }
        
    }
    
    /***
     * Downloads lectures from given url in csv format and
     * puts them in an array of Lectures
     * @param csvUrl
     * @return array of Lecture
     */
    private List<Lecture> getLectures(String csvUrl){
    	List<Lecture> values = new ArrayList<Lecture>();
    	
    	try{
	    	// open a connection to the desired URL
	        URL url = new URL(csvUrl);
	        URLConnection conn = url.openConnection();
	        
	        //use the cleaner to "clean" the HTML and return it as a TagNode object	
	        InputStreamReader isr = new InputStreamReader(conn.getInputStream());
	        BufferedReader reader = new BufferedReader(isr);

	        String line;
	        String[] splittedLine;
	        Lecture l;
	        int i = 0;
	        while ((line = reader.readLine()) != null) {
	        	if(i> 4){
	        		try{
		        		l = new Lecture();
			        	Log.d("studentportalen",line);
			        	//Startdatum, Starttid, Slutdatum, Sluttid, Kurs, Lokal, Klass, "Persongrupp, Undergrupp", Egen text, Typ 
			        	splittedLine = splitCsvLecture(line);
			        	l.setStartDate(splittedLine[0]);
			        	l.setStartTime(splittedLine[1]);
			        	l.setEndDate(splittedLine[2]);
			        	l.setEndTime(splittedLine[3]);
			        	l.setCourse(splittedLine[4]);
			        	l.setRoom(splittedLine[5]);
			        	l.setClass(splittedLine[6]);
			        	l.setGroup(splittedLine[7]);
			        	l.setText(splittedLine[8]);
			        	l.setType(splittedLine[9]);
			            values.add(l);
	        		} catch(Exception inner){
	        			//handle inner exception
	        			Log.d("studentportalen",inner.getMessage());
	        		}
	        	}
	        	i++;
	        }
	        
	        reader.close();
	        isr.close();
	        
    	} catch (Exception ex){
    		//handle exception
    		Log.d("studentportalen",ex.getMessage());
    	}
        
    	if(values.size() == 0){
    		Lecture l = new Lecture();
    		l.setCourse("No lectures planned.");
    		values.add(l);
    	}
    	
        return values;
    }
    
    /***
     * Splits the CSV values into a String array
     * 
     * String.split didn't work since some of the values in the CSV array
     * where smaller CSV array's with same delimiter
     * 
     * @param line
     * @return String of lecture values
     */
    private String[] splitCsvLecture(String line){
    	//Startdatum, Starttid, Slutdatum, Sluttid, Kurs, Lokal, Klass, "Persongrupp, Undergrupp", Egen text, Typ
    	String[] result = new String[10];
    	
    	Boolean citation = false;
    	int valueIndex = 0;
    	String value = "";
    	
    	for(int i = 0; i < line.length();i++){
    		if(line.charAt(i) == '"'){
    			//value += line.charAt(i);
    			citation = !citation;
    		}else if (citation){
    			value += line.charAt(i);
    		}else if(line.charAt(i) == ','){
    			result[valueIndex] = value;
    			valueIndex++;
    			value = "";
    		}else{
    			value += line.charAt(i);
    		}
    	}
    	
    	//split course name in to two "swedish, english"
    	String[] courses = result[4].split(",");
    	result[4] = courses[courses.length - 1];
    	
    	return result;
    }
    
}
